package com.quick.serivce.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quick.config.QuickSystem;
import com.quick.config.QuickWxMpProperties;
import com.quick.exception.QuickStateEnum;
import com.quick.mapper.WxUserLoginMapper;
import com.quick.serivce.IWxUserService;
import com.quick.util.Convert;
import com.quick.util.HttpUtil;
import com.quick.util.JSONUtil;
import com.quick.util.QuickTool;
import com.quick.util.TokenUtil;
import com.quick.wx.dto.WxUserLoginDTO;
import com.quick.wx.pojo.WxUserLogin;
import com.quick.wx.vo.WxUserLoginVo;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class WxUserServiceImpl implements IWxUserService {
	
	@Autowired
	private RedisTemplate<Object, Object> redisTemplate;
	@Autowired
	private QuickWxMpProperties wxMpProperties;
	@Autowired
	private WxUserLoginMapper wxUserLoginMapper;
	//Token 保留时间
	public static Integer iveInterval = 1000*60;

    @Override
    public void getUserInfo(String accessToken, String openId, String lang) {
        String url = String.format("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=%s", accessToken,openId,lang);
        byte[]  bytes = HttpUtil.doGet(url);
        String res = new String(bytes);
        log.info("{}",res);
    }

	@Override
	public String getAccessToken(String code) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map<String,Object> userAuth(String code) {
		System.out.println(wxMpProperties);
		String appId = wxMpProperties.getAppId();
		String appSecret = wxMpProperties.getAppSecret();
		byte[] bytes = HttpUtil.doGet("https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+appSecret+"&js_code="+code+"&grant_type=authorization_code");
		String res = new String(bytes);
		@SuppressWarnings("unchecked")
		Map<String,Object> resMap = JSONUtil.toBean(res, Map.class);
		QuickTool.isFalse(resMap.containsKey("session_key"), QuickStateEnum.LOGIN_FAIL);
		return resMap;
	}

	@Override
	public String wxLogin(WxUserLoginDTO wxLogin) {
		String token = TokenUtil.generateKey();
		String key = QuickSystem.getKey(token);
		QueryWrapper<WxUserLogin> queryWrapper = new QueryWrapper<WxUserLogin>();
		queryWrapper.lambda().eq(WxUserLogin::getOpenId, wxLogin.getOpenId());
		WxUserLogin  wxUser = wxUserLoginMapper.selectOne(queryWrapper);
		if(ObjectUtils.isEmpty(wxUser)) {
			WxUserLogin entity = Convert.convert(wxLogin, WxUserLogin.class);
			wxUserLoginMapper.insert(entity);
			redisTemplate.opsForValue().set(key, JSONUtil.toStr(entity), iveInterval,TimeUnit.SECONDS);
			return token;
		}
		redisTemplate.opsForValue().set(key, JSONUtil.toStr(wxUser), iveInterval,TimeUnit.SECONDS);
		return token;
	}

	@Override
	public WxUserLoginVo getUser() {
		String token = TokenUtil.getToken();
		String key = QuickSystem.getKey(token);
		Object res =  redisTemplate.opsForValue().get(key);
		QuickTool.isNull(res, QuickStateEnum.TOKEN_FAILURE);
		WxUserLogin result = JSONUtil.toBean(res.toString(), WxUserLogin.class);
		return wxUserLoginByOpenId(result.getOpenId());
	}

	@Override
	public WxUserLoginVo wxUserLoginByOpenId(String openId) {
		QueryWrapper<WxUserLogin> queryWrapper = new QueryWrapper<WxUserLogin>();
		queryWrapper.lambda().eq(WxUserLogin::getOpenId, openId);
		WxUserLogin  wxUser = wxUserLoginMapper.selectOne(queryWrapper);
		QuickTool.isNull(wxUser, QuickStateEnum.TOKEN_NOT_NULL);
		return Convert.convert(wxUser, WxUserLoginVo.class);
	}

	@Override
	public Boolean wxUpdateInfor(WxUserLoginDTO wxLogin) {
		QueryWrapper<WxUserLogin> queryWrapper = new QueryWrapper<WxUserLogin>();
		queryWrapper.lambda().eq(WxUserLogin::getOpenId, wxLogin.getOpenId());
		WxUserLogin login = wxUserLoginMapper.selectOne(queryWrapper);
		login.setAvatarUrl(wxLogin.getAvatarUrl());
		login.setNickName(wxLogin.getNickName());
		login.setMotto(wxLogin.getMotto());
		login.setBackImgUrl(wxLogin.getBackImgUrl());
		return wxUserLoginMapper.updateById(login)>0;
	}
}
